package com.forfunnet.minjian.ui;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.applidium.shutterbug.FetchableImageView;
import com.forfunnet.minjian.MyApplication;
import com.forfunnet.minjian.R;
import com.forfunnet.minjian.message.Product;
import com.forfunnet.minjian.message.response.BaseResponse;
import com.forfunnet.minjian.message.response.ProductDetailResponse;
import com.forfunnet.minjian.message.response.ProductListResponse;
import com.forfunnet.minjian.rest.MyRestHelper;
import com.forfunnet.minjian.ui.view.CircleImageView;
import com.forfunnet.minjian.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by RexQian on 4/4/16.
 */
@EActivity(R.layout.activity_product_detail)
public class ProductDetailActivity extends BaseActivity {

    ProductDetailResponse mResponse;

    @Extra
    int mProductId;

    @Bean
    ActivityHelper mActivityHelper;

    @ViewById(R.id.description)
    TextView mDescription;

    @ViewById(R.id.create_time)
    TextView mCreateTime;

    @ViewById(R.id.head_image)
    CircleImageView mHeadImageView;

    @ViewById(R.id.owner_name)
    TextView mOwnerName;

    @ViewById(R.id.produce_days)
    TextView mProduceDays;

    @ViewById(R.id.price)
    TextView mPrice;

    @ViewById(R.id.related_product1)
    View mRelatedProduct1;

    @ViewById(R.id.related_product2)
    View mRelatedProduct2;

    @ViewById(R.id.related_product3)
    View mRelatedProduct3;

    @ViewById(R.id.btn_concern)
    TextView mConcernButton;

    @Click(R.id.btn_concern)
    void onConcernClick()
    {
        if(mResponse != null)
        {
            onAttention(mResponse.Detail);
        }
    }

    @Background
    void onAttention (ProductDetailResponse.ProductDetail detail)
    {
        BaseResponse resp = null;
        if (detail.IsFavorite)
        {
            resp = mApp.restClient().removeProductFavorite(detail.Id);
        }
        else
        {
            resp = mApp.restClient().addProductFavorite(detail.Id);
        }
        onAttentionResult(resp, detail);
    }

    @UiThread
    void onAttentionResult (BaseResponse resp, ProductDetailResponse.ProductDetail product)
    {
        if(resp == null)
            return;

        if (BaseResponse.hasError(resp))
        {
            if (resp.ResponseStatus.Message != null)
            {
                mActivityHelper.showShortToast(resp.ResponseStatus.Message);
            }
            else
            {
                mActivityHelper.showShortToast("关注/取消关注操作异常，请重试");
            }
        }
        else
        {
            product.IsFavorite = !product.IsFavorite;

            mConcernButton.setText(product.IsFavorite?
                    R.string.cancel_concern : R.string.concern);
        }
    }

    @Click(R.id.btn_back)
    void backBtnClick ()
    {
        finish();
    }

    @AfterViews
    void init()
    {
        getDetail();
    }

    @Background
    void getDetail ()
    {
        ProductDetailResponse resp = mApp.restClient().getProductDetail(mProductId);
        updateDetail(resp);

        ProductListResponse listResponse = mApp.restClient().getProductList(0, 4,
                null, null, false);
        updateList(listResponse);
    }

    @UiThread
    void updateDetail (ProductDetailResponse resp)
    {
        mResponse = resp;

        if (BaseResponse.hasError(resp)) {
            mActivityHelper.showShortToast(BaseResponse.getErrorMessage(resp));
        }
        else {
            mDescription.setText(resp.Detail.Description);
            mCreateTime.setText(CommonUtils.mDateFormat.format(resp.Detail.CreateTime));
            mHeadImageView.setImage(MyRestHelper.ProductImageHeadUrl(mApp.restClient(),
                    resp.Detail.Id));
            mOwnerName.setText(resp.Detail.OwnerId == 0 ? getString(R.string.official)
                    : resp.Detail.OwnerName);
            mProduceDays.setText(String.format(getString(R.string.format_day),
                    resp.Detail.ProduceDays));
            mPrice.setText(String.format("%.2f", resp.Detail.Price/100f));

            mConcernButton.setText(resp.Detail.IsFavorite?
                    R.string.cancel_concern : R.string.concern);
        }
    }

    @UiThread
    void updateList(ProductListResponse response)
    {
        if(BaseResponse.hasError(response))
            return;

        View[] viewList = new View[]{
                mRelatedProduct1,
                mRelatedProduct2,
                mRelatedProduct3
        };

        List<Product> productList = response.DataList;
        for (int i = 0; i < productList.size(); i++)
        {
            if(mProductId == productList.get(i).Id)
            {
                productList.remove(i);
                break;
            }
        }


        for (int i = 0; i < viewList.length && i < productList.size(); i++)
        {
            Product product = response.DataList.get(i);

            viewList[i].setVisibility(View.VISIBLE);

            ((FetchableImageView) viewList[i].findViewById(R.id.cover))
            .setImage(MyRestHelper.ProductImageUrl(mApp.restClient(),
                    product.Id));
            ((TextView) viewList[i].findViewById(R.id.content)).setText(product.Name);

            viewList[i].setTag(product);

            viewList[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Product product1 = (Product) v.getTag();
                    ProductDetailActivity_.intent(ProductDetailActivity.this)
                            .mProductId(product1.Id).start();
                }
            });
        }
    }
}
